/**
 * Created by wangmeng on 2018/8/15.
 */
var param = new Object();
var map = {};//存储单元格信息(map形式，key是分区、value是该分区所有的单元格信息)
var url = path + "/common/excelImport/listByPage";
$(function () {
    setExcelValue();
    var cellgrid = $("#celltt");
    initCellGrid(cellgrid);
    cellgrid.datagrid({
        fit:false
    });
    cellgrid.datagrid("resize",{
        height:440
    });
    initCellData();
});

//设置导出excel的字段信息
function setExcelValue(){
    var item = excelJson[0];
    $('#excelId').val(item['excelId']);
    $('#excelCode').val(item['excelCode']);
    $('#tableName').val(item['tableName']);
    $("#template").val(item['template']);
    $('#sheetNo').val(item['sheetNo']);
    $('#startRow').val(item['startRow']);
}

//初始化单元格定义表格和数据
var dataSourceOption = [{ "value": 1, "text": "读取excel" }, { "value": 2, "text": "数据映射" }, { "value": 3, "text": "系统生成" }];
function initCellGrid(grid,flag) {
    var columns = [
        {
            field: "cellId", title: "ID", hidden: true,
            align: "left", sortable: false, resizable: true, width: 120
        },
        {
            field: "excelId", title: "ID", hidden: true,
            align: "left", sortable: false, resizable: true, width: 120
        },
        {
            field: "columnName",
            title: "数据库表字段",
            align: "left",
            halign: "center",
            sortable: false,
            resizable: true,
            width: 100
        },
        {
            field: "dataSource",
            title: "数据来源 ",
            align: "left",
            halign: "center",
            editor:{ type: 'combobox', options: {
                    data: dataSourceOption,
                    valueField: "value",
                    textField: "text",
                    editable: false,
                    required: true,
                    panelHeight: "auto"
                } },
            sortable: false,
            resizable: true,
            width: 100,
            formatter: function (value, row, index) {
                var dataSource = "";
                if(value == 1) {
                    dataSource = "读取excel";
                }else if(value == 2) {
                    dataSource = "数据映射";
                }else if(value == 3) {
                    dataSource = "系统生成"
                }
                return dataSource;
            }
        },
        {
            field: "excelColumn",
            title: "excel列名",
            align: "left",
            halign: "center",
            editor:{ type: 'textbox' },
            sortable: false,
            resizable: true,
            width: 100
        },
        {
            field: "excelColumnNo",
            title: "excel列号",
            align: "left",
            halign: "center",
            editor:{ type: 'numberbox', options: {min:0}},
            sortable: false,
            resizable: true,
            width: 80
        },
        {
            field: "mapperTable",
            title: "映射表名",
            align: "left",
            halign: "center",
            editor:{ type: 'textbox' },
            sortable: false,
            resizable: true,
            width: 150
        },
        {
            field: "fetchField",
            title: "取数字段",
            align: "left",
            halign: "center",
            editor:{ type: 'textbox' },
            sortable: false,
            resizable: true,
            width: 100
        },
        {
            field: "mapperField",
            title: "映射字段",
            align: "left",
            halign: "center",
            editor:{ type: 'textbox' },
            sortable: false,
            resizable: true,
            width: 100
        },
        {
            field: "condition",
            title: "过滤条件",
            align: "left",
            halign: "center",
            editor:{ type: 'textbox' },
            sortable: false,
            resizable: true,
            width: 400
        }
    ];
    initGridWithCheckBoxCanEdit(grid, param, url, columns, "#celltb", "id");
    var options = $("#celltt").datagrid("options");
    options.onLoadSuccess = function (data) {
        $("#celltt").datagrid("fixRownumber");
    };
    grid.datagrid({
        title:'表字段信息'
    });
}

/**
 * 初始化 DataGrid控件信息带checkbox多选不分页 (默认选中)
 *
 * @param grid
 */
function initGridWithCheckBoxCanEdit(grid, params, url, columns, toolbar, fieldId) {
    // 初始化 DataGrid控件信息
    grid.datagrid({
        url : "",
        title : "",
        toolbar : toolbar,
        onClickCell: onClickCell,
        onAfterEdit: onAfterEdit,
        fit:false,
        loadMsg : "",
        queryParams : {},
        nowrap : true,
        striped : true,
        idField : fieldId,
        remoteSort : false,
        frozenColumns : [ [ {
            field : 'check',
            checkbox : true
        } ] ],
        columns : [ columns ],
        onLoadSuccess : function(data) {
            grid.datagrid('clearSelections');
        },
        onLoadError : function() {
            $("#loading").hide();
        }
    });
}

//初始化单元格信息
function initCellData() {
    if (cellJson && cellJson.length > 0) {
        $("#celltt").datagrid("loadData", cellJson);
    }else {
        $("#celltt").datagrid('loadData', {total : 0, rows : []});
    }
}

//新增全部
function btnAddAllCell() {
    var tableName = $.trim($("#tableName").val());
    if(tableName == ""){
        $.messager.alert("提示", "请先填写导入表名！", "info");
        return false;
    }
    var rows = $('#celltt').datagrid('getRows');
    if(rows.length>0){
        $.messager.confirm("操作提示", "已存在数据，是否删除并新增全部?", function (OK) {
            if (OK) {
                $('#celltt').datagrid('loadData',{total:0,rows:[]});
                addAllCell(tableName);
            }
        });
    }else {
        addAllCell(tableName);
    }
}
//新增所有表字段信息
function addAllCell(tableName) {
    var selectParams = new Object();
    selectParams.tableName =  tableName.toUpperCase();
    var selectUrl = path + "/common/excelImport/listTableColumnByName";
    $.ajax({
        type : "POST",
        url : selectUrl,
        data : selectParams,
        dataType : "json",
        success : function callback(data) {
            var analyMsg = data;
            if(analyMsg.code = "0000"){
                if (analyMsg.returnObject.total > 0) {
                    for(var i=0;i<analyMsg.returnObject.total;i++){
                        var tableColumn = analyMsg.returnObject.rows[i];
                        var newRow = new Object();
                        newRow.columnName = tableColumn.columnName;
                        newRow.dataSource = 1;
                        $("#celltt").datagrid('appendRow', newRow);
                    }
                } else {
                    $.messager.alert("提示", "未查询到表字段信息，请检查导入表名是否正确！", "info");
                }
            }
        },
        error : function(data, textstatus) {
            $.messager.alert("default", data.responseText,"error" );
        }
    });
}

//新增表字段信息
function btnAddCell() {
    var tableName = $.trim($("#tableName").val());
    if(tableName == ""){
        $.messager.alert("提示", "请先填写导入表名！", "info");
        return false;
    }
    top.layer.open({
        type: 2,
        title: '新增表字段',
        shadeClose: false,
        shade: 0.3,
        area: ['650px', '400px'],
        content: path+'/common/excelImport/toAddCell?tableName='+tableName.toUpperCase(), //iframe的url
        maxmin: false,
        end: function callback() {
            var cellRows = getGlobalVariable("cellRow");
            var cellRow = JSON.parse(cellRows)[0];
            $("#celltt").datagrid('appendRow', cellRow);
        }
    });
}

//修改表字段信息
function btnEditCell() {
    var tableName = $.trim($("#tableName").val());
    if(tableName == ""){
        $.messager.alert("提示", "请先填写导入表名！", "info");
        return false;
    }
    var selectedItem = $('#celltt').datagrid('getSelected');
    if(!selectedItem){
        $.messager.alert("提示", "请选择需要修改的记录！", "info");
        return false;
    }
    var rows = $('#celltt').datagrid('getSelections');
    if (rows.length != 1) {
        $.messager.alert("提示", "请选择一条记录！", "info");
        return false;
    }
    var index = $("#celltt").datagrid('getRowIndex', selectedItem);
    var cellRows = [];    //设置完成的信息，用于界面间的传值
    cellRows.push(selectedItem);
    setGlobalVariable("cellRow",JSON.stringify(cellRows));
    top.layer.open({
        type: 2,
        title: '修改分区',
        sshadeClose: false,
        shade: 0.3,
        area: ['650px', '400px'],
        content: path+'/common/excelImport/toAddCell?tableName='+tableName.toUpperCase(), //iframe的url
        maxmin: false,
        end: function callback() {
            var cellRows = getGlobalVariable("cellRow");
            var cellRow = JSON.parse(cellRows)[0];
            $('#celltt').datagrid('updateRow', {index: index, row: cellRow});
        }
    });
}

//删除单元格信息
function  btnDelCell() {
    var rows = $('#celltt').datagrid('getSelections');
    if (rows.length == 0) {
        $.messager.alert("操作提示", "请选一条记录！", "info");
        return false;
    }else{
        $.messager.confirm("操作提示", "是否要删除选中的表字段信息?", function (OK) {
            if(OK){
                var deletedData = $('#celltt').datagrid('getChecked');
                var deletedDataLength = deletedData.length;
                for(var i=0;i<deletedDataLength;i++){
                    var rowIndex = $('#celltt').datagrid('getRowIndex', deletedData[0]);
                    $('#celltt').datagrid('deleteRow', rowIndex);
                }
            }
        });
    }
}

$.extend($.fn.datagrid.methods, {
    editCell: function(jq,param){
        return jq.each(function(){
            var opts = $('#celltt').datagrid('options');
            var fields = $('#celltt').datagrid('getColumnFields',true).concat($('#celltt').datagrid('getColumnFields'));
            for(var i=0; i<fields.length; i++){
                var col = $('#celltt').datagrid('getColumnOption', fields[i]);
                col.editor1 = col.editor;
                if (fields[i] != param.field){
                    col.editor = null;
                }
            }
            $('#celltt').datagrid('beginEdit', param.index);
            for(var i=0; i<fields.length; i++){
                var col = $('#celltt').datagrid('getColumnOption', fields[i]);
                col.editor = col.editor1;
            }
        });
    }
});

var editIndex = undefined;
function endEditing(){
    if (editIndex == undefined){return true}
    if ($('#celltt').datagrid('validateRow', editIndex)){
        $('#celltt').datagrid('endEdit', editIndex);
        editIndex = undefined;
        return true;
    } else {
        return false;
    }
}
function onClickCell(index, field){
    if (endEditing()){
        $('#celltt').datagrid('selectRow', index)
            .datagrid('editCell', {index:index,field:field});
        editIndex = index;
    }
}
//单元格失去焦点执行的方法
function onAfterEdit(index, row, changes) {}

//保存增加的数据
function submit_Add() {
    if (!validform("user_form")) {
        return false;
    }
    var sheetNo = $.trim($("#sheetNo").val());
    if(isNaN(sheetNo)){
        $.messager.alert("提示", "sheet索引必须是零或正整数！", "info");
        return false;
    }
    var startRow = $.trim($("#startRow").val());
    if(isNaN(startRow)){
        $.messager.alert("提示", "数据起始行必须是零或正整数！", "info");
        return false;
    }
    var finalParams = new Object();
    finalParams.type = "edit";
    finalParams.excelId = excelId;
    finalParams.excelCode = $.trim($("#excelCode").val());
    finalParams.tableName = $.trim($("#tableName").val());
    finalParams.template = $.trim($("#template").val());
    finalParams.sheetNo = sheetNo;
    finalParams.startRow = startRow;
    var cellRows = $('#celltt').datagrid('getRows');
    var columnNames = [];
    var flag = "0";
    $.each(cellRows, function (index, item) {
        if(columnNames.indexOf(item.columnName) != -1){
            flag = "1";
            $.messager.alert("提示", "表字段为"+item.columnName+"的数据重复，请检查！", "info");
            return false;
        }
        columnNames.push(item.columnName);
    });
    if(flag == "1"){
        return false;
    }
    var cellRowsData = JSON.stringify(cellRows);
    finalParams.cellList = cellRowsData;
    $.ajax({
        type: "POST",
        url: path+'/common/excelImport/save',
        data: finalParams,
        dataType: "json",
        success: function callback(data) {
            var analyMsg = data;
            if (analyMsg.code != '0000') {
                $.messager.alert('操作提示', analyMsg.msg, 'warning', function () {
                });
            } else {
                $.messager.alert("操作提示", "修改导入定义成功.", "info", function () {
                    closeLayer();
                });
            }
        },
        error: function (data, textstatus) {
            $.messager.alert('操作提示', data.responseText, 'error', function () {
            });
        }
    });
}